package com.top.horizon.th1804app.ui.fragment;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import com.net.protocol.model.CommonModel;
import com.net.protocol.model.DeviceInfoModel;
import com.net.protocol.model.FileTag;
import com.net.protocol.model.RecordFile;
import com.top.horizon.th1804app.R;
import com.top.horizon.th1804app.adapter.PlayBackAdapter;
import com.top.horizon.th1804app.adapter.TagAdapter;
import com.top.horizon.th1804app.base.BaseFragment;
import com.net.protocol.NetController;
import com.top.horizon.th1804app.manager.FileManage;
import com.top.horizon.th1804app.view.TagLinearLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class PlayBackFragment extends BaseFragment implements View.OnClickListener, PlayBackAdapter.onPlayAdapterListener {
    private RecyclerView rvPlayList;
    private PlayBackAdapter playBackAdapter;
    private RecordFile mSelctedFile;
    private TagLinearLayout tagLinearLayout;
    private SeekBar seekBar;
    private int searchFileTAG = -1;
    private View tagView;
    private RecyclerView rlvTag;
    private TagAdapter tagAdapter;
    private ImageView ivBtn;

    private Handler mHandler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {

        }
    };
    //0：实时播放；1：设备回放
    //2：回放暂停
    private int devicePlayStatus;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_playback;
    }

    @Override
    protected void initView() {
        rvPlayList = rootView.findViewById(R.id.rv_playlist);
        rvPlayList.setLayoutManager(new LinearLayoutManager(this.getContext()));
        seekBar = rootView.findViewById(R.id.seek_bar_play_progress);
        tagLinearLayout = rootView.findViewById(R.id.ll_tag_root);
        ivBtn = rootView.findViewById(R.id.iv_play_btn);
        ivBtn.setOnClickListener(this);
        rootView.findViewById(R.id.iv_play_stop_btn).setOnClickListener(this);
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if (mSelctedFile != null){
                    showProgressLoadingDialog();
                    Log.i("test", "i = " + i);
                    NetController.playFile(mSelctedFile.name, i);
                    //test start
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            EventBus.getDefault().post(new CommonModel());
                        }
                    }, 2_000);
                    //test end
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        //-------------tags view-----------------//
        tagView = View.inflate(getContext(), R.layout.tag_list_dialog, null);
        rlvTag = tagView.findViewById(R.id.rlv_tags);

    }

    @Override
    protected void initData() {

        rvPlayList.addItemDecoration(new DividerItemDecoration(this.getContext(), DividerItemDecoration.VERTICAL));
        playBackAdapter = new PlayBackAdapter(FileManage.getInstance().getPlayData(), this.getContext());
        playBackAdapter.setListener(this);
        rvPlayList.setAdapter(playBackAdapter);

        //---------tag list--------------------//
        rlvTag.setLayoutManager(new LinearLayoutManager(getContext()));
        rlvTag.addItemDecoration(new DividerItemDecoration(getContext(), DividerItemDecoration.VERTICAL));
        tagAdapter = new TagAdapter(getContext());
        rlvTag.setAdapter(tagAdapter);
        tagAdapter.setListener(new TagAdapter.ItemClickListener() {
            @Override
            public void onClick(int position, FileTag.Tag tag) {
                mSelctedFile.clearTagSelected();
                tag.selected = true;
                //从此标签处开始播放
                tagLinearLayout.refresh();
                //请求网络
                showProgressLoadingDialog();
                NetController.playFile(tag.name, tag.positon);
                //test start
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        EventBus.getDefault().post(new CommonModel());
                    }
                },2_000);
                //test end
                dismissDialog();
            }
        });

    }

    /**
     * 对话框内的点击监听
     *
     * @param view
     * @param mLayoutId
     */
    @Override
    public void onClickChildView(View view, int mLayoutId) {
        view.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dismissDialog();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        //查询要播放的文字标签
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        //判断是不是需要请求播放
        final RecordFile file = FileManage.getInstance().getPlayData().get(0);
        if (file.playState == 1) {
            showProgressLoadingDialog();
            NetController.playFile(file.name, 0);
            NetController.searchFileTAG(file.name);
            setShowUI(0, file);
            //test start
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    EventBus.getDefault().post(new CommonModel());
                }
            },2_000);
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    FileTag fileTag =new FileTag();
                    fileTag.code = 0;
                    fileTag.seqId = 0;
                    FileTag.Tag tag = fileTag.new Tag();
                    tag.name = "name+0";
                    tag.positon = 100;
                    tag.tag = "aaaaaaa";
                    FileTag.Tag tag2 = fileTag.new Tag();
                    tag2.positon = 200;
                    tag2.tag = "bbbbbb";
                    FileTag.Tag tag1 = fileTag.new Tag();
                    tag1.positon = 500;
                    tag1.tag = "aaaaacccccaa";
                    List<FileTag.Tag> list = new ArrayList<>();
                    list.add(tag);
                    list.add(tag1);
                    list.add(tag2);
                    fileTag.tags = list;
                    EventBus.getDefault().post(fileTag);
                }
            },2_000);
            //test end
        }else {
            RecordFile playSelected = FileManage.getInstance().getPlaySelected();
            int playSelectedIndex = FileManage.getInstance().getPlaySelectedIndex();
            setShowUI(playSelectedIndex,playSelected);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void CommonEvent(CommonModel commonAck) {
        dismissProgressLoadingDialog();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void heartEvent(DeviceInfoModel model) {
        devicePlayStatus = model.playStatus;
        //回放
        if (model.playStatus == 1) {
            FileManage.getInstance().changePlayFile(model.playFileName, model.position);
            if (mSelctedFile!= null && mSelctedFile.name.equals(model.playFileName)){
                ivBtn.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_pause));
                seekBar.setProgress(model.position);
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void searchTagEvent(FileTag tags) {
        FileManage.getInstance().addFileTag(tags.tags);
        //判断当前显示界面是不是本文件
        if (mSelctedFile != null && tags != null && tags.tags.size() != 0) {
            if (mSelctedFile.name.equals(tags.tags.get(0).name)) {
                //设置标签
                tagLinearLayout.setTags(tags.tags);
                tagLinearLayout.refresh();
            }
        }
        //判断是不是长按的返回结果
        if (tags.seqId == searchFileTAG) {
            dismissProgressLoadingDialog();
            if (tags.tags != null && tags.tags.size() > 0) {
                tagAdapter.setData(tags.tags);
                showDialog(tagView);
            } else {
                showToast("没有标签信息");
            }
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_play_btn:
                if (mSelctedFile.playState == 2) {
                    ivBtn.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_play));
                    //停止播放
                    showProgressLoadingDialog();
                    NetController.pausePlay(mSelctedFile.name);
                }else {
                    ivBtn.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_pause));
                    //停止播放
                    showProgressLoadingDialog();
                    NetController.playFile(mSelctedFile.name,0);
                }
                break;
            case R.id.iv_play_stop_btn:
                if (devicePlayStatus == 0){
                    showToast("设备没有在回放");
                    return;
                }
                NetController.stopPlay();
                break;
        }
        //test start
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                EventBus.getDefault().post(new CommonModel());
            }
        },2_000);
        //test end

    }

    @Override
    public void deleteFile(int position, RecordFile file) {
        FileManage.getInstance().removeFromPlay(position, file);
        playBackAdapter.notifyDataSetChanged();
    }

    @Override
    public void clickItem(int position, RecordFile file) {
        setShowUI(position, file);
    }

    @Override
    public void longClickItem(int position, RecordFile file) {
        setShowUI(position, file);
        if (file.tags == null || file.tags.size() == 0) {
            showProgressLoadingDialog();
            searchFileTAG = NetController.searchFileTAG(file.name);
            //test start
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    FileTag fileTag =new FileTag();
                    fileTag.code = 0;
                    fileTag.seqId = 0;
                    FileTag.Tag tag = fileTag.new Tag();
                    tag.name = "name+0";
                    tag.positon = 100;
                    tag.tag = "aaaaaaa";
                    FileTag.Tag tag2 = fileTag.new Tag();
                    tag2.positon = 200;
                    tag2.tag = "bbbbbb";
                    FileTag.Tag tag1 = fileTag.new Tag();
                    tag1.positon = 500;
                    tag1.tag = "aaaaacccccaa";
                    List<FileTag.Tag> list = new ArrayList<>();
                    list.add(tag);
                    list.add(tag1);
                    list.add(tag2);
                    fileTag.tags = list;
                    EventBus.getDefault().post(fileTag);

                }
            },2_000);
            //test end
            return;
        }else {
            tagAdapter.setData(file.tags);
            showDialog(tagView);
        }
    }

    private void setShowUI(int position, RecordFile file) {
        mSelctedFile = file;
        playBackAdapter.setSelected(position);
        seekBar.setMax(file.size);
        seekBar.setProgress(file.playPosition);
        tagLinearLayout.setTotalSize(file.size);
        tagLinearLayout.setTags(file.tags);
        if (file.playState == 2){
            ivBtn.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_pause));
        }else {
            ivBtn.setImageDrawable(getContext().getResources().getDrawable(R.mipmap.icon_play));
        }
    }
}
